import React, { useState, useEffect, useRef, useCallback } from 'react';
import { 
  Row, 
  Col, 
  Statistic, 
  Progress, 
  Timeline, 
  Tag, 
  Button,
  Spin,
  Divider,
  Space,
  Tooltip,
  Badge,
  Avatar,
  Skeleton
} from 'antd';
import {
  UserOutlined,
  CheckCircleOutlined,
  SyncOutlined,
  CloseCircleOutlined,
  RobotOutlined,
  BugOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  ReloadOutlined,
  CloudUploadOutlined,
  CloudDownloadOutlined,
  DatabaseOutlined,
  ApiOutlined,
  ClockCircleOutlined,
  RiseOutlined,
  FallOutlined,
  ThunderboltOutlined,
  DashboardOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  FundOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  FireOutlined,
  TrophyOutlined,
  RocketOutlined
} from '@ant-design/icons';
import { motion, AnimatePresence } from 'framer-motion';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import { apiClient } from '../../services/apiClient';
import { notification } from '../common';
import CountUp from 'react-countup';

// 导入自定义图表组件
import CustomLineChart from '../charts/CustomLineChart';
import CustomPieChart from '../charts/CustomPieChart';
import CustomColumnChart from '../charts/CustomColumnChart';

// 数据接口定义
interface DashboardStats {
  total_users: number;
  active_users: number;
  total_tasks: number;
  running_tasks: number;
  completed_tasks: number;
  failed_tasks: number;
  total_crawlers: number;
  running_crawlers: number;
  ai_models: number;
  active_models: number;
  data_volume: string;
  daily_requests: number;
  success_rate: number;
}

interface SystemStats {
  cpu_usage: number;
  memory_usage: number;
  memory_total: number;
  memory_used: number;
  disk_usage: number;
  disk_total: number;
  disk_used: number;
  network_sent: number;
  network_recv: number;
  processes: number;
  uptime_days: number;
  uptime_hours: number;
  uptime_minutes: number;
}

interface ActivityItem {
  id: number;
  type: string;
  title: string;
  description: string;
  timestamp: string;
  status: string;
  user_id: number;
}

interface QuickStatsItem {
  tasks_completed: number;
  data_processed: string;
  api_calls: number;
  success_rate: number;
}

interface QuickStatsData {
  today: QuickStatsItem;
  yesterday: QuickStatsItem;
  this_week: QuickStatsItem;
  this_month: QuickStatsItem;
}

// 自定义卡片组件
const CustomCard: React.FC<{
  children: React.ReactNode;
  style?: React.CSSProperties;
  bodyStyle?: React.CSSProperties;
  theme: any; // 添加theme属性
  mode: any;  // 添加mode属性
}> = ({ children, style, bodyStyle, theme, mode }) => {
  // 根据主题模式设置背景色
  const getCardBackground = () => {
    if (mode === 'light') {
      return 'rgba(255, 255, 255, 0.95)'; // 浅色主题时使用更透明白色背景
    }
    // 深色主题时使用更深的背景色
    return 'rgba(20, 20, 20, 0.9)';
  };
  
  return (
    <div
      style={{
        background: getCardBackground(),
        border: `1px solid ${theme.cardBorder}`,
        borderRadius: '16px',
        overflow: 'hidden',
        position: 'relative',
        boxShadow: theme.cardShadow,
        backdropFilter: 'blur(15px)', // 增强毛玻璃效果
        ...style
      }}
    >
      <div style={{ padding: '20px', ...bodyStyle }}>
        {children}
      </div>
    </div>
  );
};

const EnhancedDashboard: React.FC = () => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);

  // 定义图标颜色，根据主题模式设置
  const iconColors = {
    success: '#52c41a',
    error: '#ff4d4f',
    warning: '#faad14',
    processing: '#1890ff',
    purple: mode === 'dark' ? '#9254de' : '#722ed1',
    default: mode === 'dark' ? 'rgba(255, 255, 255, 0.85)' : '#1890ff'
  };

  const [dashboardStats, setDashboardStats] = useState<DashboardStats | null>(null);
  const [systemStats, setSystemStats] = useState<SystemStats | null>(null);
  const [activities, setActivities] = useState<ActivityItem[]>([]);
  const [quickStats, setQuickStats] = useState<QuickStatsData | null>(null);
  const [loading, setLoading] = useState({
    dashboard: true,
    system: true,
    activities: true,
    quick: true
  });
  const [isRefreshing, setIsRefreshing] = useState(false);

  const refreshTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const mountedRef = useRef(false);

  // 设置mounted标志
  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);

  // 获取控制台统计数据
  const fetchDashboardStats = useCallback(async () => {
    try {
      setLoading(prev => ({ ...prev, dashboard: true }));
      const data = await apiClient.get<DashboardStats>('/dashboard/stats');
      setDashboardStats(data);
    } catch (error: any) {
      console.error('获取控制台统计数据失败:', error);
      notification.error({
        title: '数据获取失败',
        message: `获取控制台统计数据失败: ${error.message || '未知错误'}`
      });
    } finally {
      setLoading(prev => ({ ...prev, dashboard: false }));
    }
  }, []);

  // 获取系统状态信息
  const fetchSystemStats = useCallback(async () => {
    try {
      setLoading(prev => ({ ...prev, system: true }));
      const data = await apiClient.get<SystemStats>('/dashboard/system');
      setSystemStats(data);
    } catch (error: any) {
      console.error('获取系统状态信息失败:', error);
      notification.error({
        title: '数据获取失败',
        message: `获取系统状态信息失败: ${error.message || '未知错误'}`
      });
    } finally {
      setLoading(prev => ({ ...prev, system: false }));
    }
  }, []);

  // 获取最近活动记录
  const fetchActivities = useCallback(async () => {
    try {
      setLoading(prev => ({ ...prev, activities: true }));
      const data = await apiClient.get<{ activities: ActivityItem[] }>('/dashboard/activities');
      setActivities(data.activities);
    } catch (error: any) {
      console.error('获取活动记录失败:', error);
      notification.error({
        title: '数据获取失败',
        message: `获取活动记录失败: ${error.message || '未知错误'}`
      });
    } finally {
      setLoading(prev => ({ ...prev, activities: false }));
    }
  }, []);

  // 获取快速统计信息
  const fetchQuickStats = useCallback(async () => {
    try {
      setLoading(prev => ({ ...prev, quick: true }));
      const data = await apiClient.get<{ data: QuickStatsData }>('/dashboard/quick-stats');
      setQuickStats(data.data);
    } catch (error: any) {
      console.error('获取快速统计信息失败:', error);
      notification.error({
        title: '数据获取失败',
        message: `获取快速统计信息失败: ${error.message || '未知错误'}`
      });
    } finally {
      setLoading(prev => ({ ...prev, quick: false }));
    }
  }, []);

  // 刷新所有数据
  const refreshAllData = useCallback(() => {
    setIsRefreshing(true);

    // 防止频繁刷新
    if (refreshTimeoutRef.current) {
      clearTimeout(refreshTimeoutRef.current);
    }

    refreshTimeoutRef.current = setTimeout(() => {
      fetchDashboardStats();
      fetchSystemStats();
      fetchActivities();
      fetchQuickStats();

      setTimeout(() => {
        setIsRefreshing(false);
      }, 1000);
    }, 300);
  }, [fetchDashboardStats, fetchSystemStats, fetchActivities, fetchQuickStats]);

  // 初始化数据
  useEffect(() => {
    fetchDashboardStats();
    fetchSystemStats();
    fetchActivities();
    fetchQuickStats();
  }, [fetchDashboardStats, fetchSystemStats, fetchActivities, fetchQuickStats]);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (refreshTimeoutRef.current) {
        clearTimeout(refreshTimeoutRef.current);
      }
    };
  }, []);

  // 获取活动类型图标 - 修复Hooks违规问题，将theme和mode作为参数传入
  const getActivityIcon = (type: string, status: string, iconColors: any) => {
    const iconStyle = { fontSize: '18px' };

    switch (type) {
      case 'task':
        return status === 'success' ?
          <CheckCircleOutlined style={{ ...iconStyle, color: iconColors.success }} /> :
          status === 'error' ?
          <CloseCircleOutlined style={{ ...iconStyle, color: iconColors.error }} /> :
          <SyncOutlined style={{ ...iconStyle, color: iconColors.processing }} spin />;
      case 'system':
        return <CloudUploadOutlined style={{ ...iconStyle, color: iconColors.purple }} />;
      case 'user':
        return <UserOutlined style={{ ...iconStyle, color: iconColors.processing }} />;
      case 'alert':
        return <WarningOutlined style={{ ...iconStyle, color: iconColors.warning }} />;
      case 'crawler':
        return <BugOutlined style={{ ...iconStyle, color: iconColors.success }} />;
      default:
        return <InfoCircleOutlined style={{ ...iconStyle, color: iconColors.default }} />;
    }
  };

  // 获取活动状态标签
  const getActivityTag = (status: string) => {
    const tagStyle = { borderRadius: '12px', padding: '2px 12px' };
    switch (status) {
      case 'success':
        return <Tag color="success" style={tagStyle}>成功</Tag>;
      case 'error':
        return <Tag color="error" style={tagStyle}>错误</Tag>;
      case 'warning':
        return <Tag color="warning" style={tagStyle}>警告</Tag>;
      case 'running':
        return <Tag color="processing" style={tagStyle}>运行中</Tag>;
      case 'info':
        return <Tag color="default" style={tagStyle}>信息</Tag>;
      default:
        return <Tag color="default" style={tagStyle}>{status}</Tag>;
    }
  };

  // 格式化时间
  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days > 0) {
      return `${days}天前`;
    } else if (hours > 0) {
      return `${hours}小时前`;
    } else if (minutes > 0) {
      return `${minutes}分钟前`;
    } else {
      return '刚刚';
    }
  };

  // 统计卡片组件
  const StatCard = ({ title, value, prefix, suffix, color, subValue, subLabel, delay, trend }: any) => (
    <motion.div
      initial={{ y: 20, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      transition={{ delay, type: "spring", stiffness: 100 }}
      whileHover={{
        y: -5,
        transition: { duration: 0.2 }
      }}
    >
      <CustomCard
        theme={theme}
        mode={mode}
        style={{
          height: '100%',
          overflow: 'hidden',
          position: 'relative',
        }}
      >
        {/* 背景装饰 */}
        <div style={{
          position: 'absolute',
          top: '-30px',
          right: '-30px',
          width: '100px',
          height: '100px',
          borderRadius: '50%',
          background: `radial-gradient(circle, ${color}20 0%, transparent 70%)`,
          filter: 'blur(30px)',
          pointerEvents: 'none',
        }} />

        <div style={{ position: 'relative', zIndex: 1 }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            marginBottom: '16px',
            gap: '12px'
          }}>
            <div style={{
              width: '40px',
              height: '40px',
              borderRadius: '12px',
              background: `linear-gradient(135deg, ${color}20 0%, ${color}10 100%)`,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '20px',
              color: color,
            }}>
              {prefix}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{
                fontSize: '12px',
                color: theme.textSecondary,
                marginBottom: '4px',
                textTransform: 'uppercase',
                letterSpacing: '0.5px'
              }}>
                {title}
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px' }}>
                <CountUp
                  end={value}
                  duration={2}
                  separator=","
                  suffix={suffix}
                  style={{
                    fontSize: '24px',
                    fontWeight: 'bold',
                    color: theme.textPrimary
                  }}
                />
                {trend && (
                  <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    fontSize: '12px',
                    color: trend > 0 ? '#52c41a' : '#ff4d4f'
                  }}>
                    {trend > 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                    {Math.abs(trend)}%
                  </div>
                )}
              </div>
            </div>
          </div>

          {subValue !== undefined && (
            <div style={{
              padding: '8px 12px',
              background: `${color}08`,
              borderRadius: '8px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              borderLeft: `3px solid ${color}`,
            }}>
              <span style={{ fontSize: '12px', color: theme.textSecondary }}>
                {subLabel}
              </span>
              <span style={{
                fontSize: '14px',
                fontWeight: '600',
                color: color
              }}>
                <CountUp end={subValue} duration={2} separator="," />
              </span>
            </div>
          )}
        </div>
      </CustomCard>
    </motion.div>
  );

  // 系统监控项组件
  const SystemMonitorItem = ({ label, value, total, icon, color }: any) => {
    const percentage = total ? (value / total) * 100 : value;

    return (
      <motion.div
        initial={{ opacity: 0, x: -20 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ type: "spring", stiffness: 100 }}
        style={{
          padding: '16px',
          borderRadius: '12px',
          background: `linear-gradient(135deg, ${color}05 0%, ${color}10 100%)`,
          border: `1px solid ${color}20`,
          marginBottom: '16px',
          position: 'relative',
          overflow: 'hidden',
        }}
        whileHover={{
          scale: 1.02,
          transition: { duration: 0.2 }
        }}
      >
        <div style={{
          display: 'flex',
          alignItems: 'center',
          marginBottom: '12px'
        }}>
          <div style={{
            fontSize: '20px',
            color: color,
            marginRight: '12px',
            width: '32px',
            height: '32px',
            borderRadius: '8px',
            background: `${color}15`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            {icon}
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: '14px', color: theme.textPrimary, fontWeight: '500' }}>
              {label}
            </div>
            {total && (
              <div style={{ fontSize: '12px', color: theme.textSecondary, marginTop: '2px' }}>
                {value.toFixed(1)} / {total.toFixed(1)} GB
              </div>
            )}
          </div>
          <div style={{
            fontSize: '18px',
            fontWeight: 'bold',
            color: percentage > 80 ? '#ff4d4f' : percentage > 60 ? '#faad14' : color,
          }}>
            {percentage.toFixed(1)}%
          </div>
        </div>

        <div style={{ position: 'relative' }}>
          <div style={{
            height: '8px',
            background: `${theme.cardBorder}40`,
            borderRadius: '4px',
            overflow: 'hidden',
          }}>
            <motion.div
              initial={{ width: 0 }}
              animate={{ width: `${percentage}%` }}
              transition={{ duration: 1, ease: "easeOut" }}
              style={{
                height: '100%',
                background: `linear-gradient(90deg, ${color} 0%, ${color}dd 100%)`,
                borderRadius: '4px',
                boxShadow: `0 2px 8px ${color}40`,
              }}
            />
          </div>
        </div>
      </motion.div>
    );
  };

  // 快速统计卡片
  const QuickStatCard = ({ title, data, icon, color }: any) => (
    <motion.div
      whileHover={{ scale: 1.03 }}
      transition={{ type: "spring", stiffness: 300 }}
    >
      <CustomCard
        theme={theme}
        mode={mode}
        style={{
          height: '100%',
          position: 'relative',
          overflow: 'hidden',
        }}
        bodyStyle={{ padding: '16px' }}
      >
        <div style={{
          position: 'absolute',
          top: '8px',
          right: '8px',
          fontSize: '32px',
          color: `${color}20`,
        }}>
          {icon}
        </div>

        <div style={{
          fontSize: '13px',
          color: theme.textSecondary,
          marginBottom: '12px',
          fontWeight: '500',
          display: 'flex',
          alignItems: 'center',
          gap: '6px'
        }}>
          <span style={{
            width: '6px',
            height: '6px',
            borderRadius: '50%',
            background: color,
            display: 'inline-block'
          }} />
          {title}
        </div>

        <div style={{ textAlign: 'center', marginBottom: '16px' }}>
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ type: "spring", stiffness: 200, delay: 0.2 }}
            style={{
              fontSize: '28px',
              fontWeight: 'bold',
              color: color,
              marginBottom: '4px'
            }}
          >
            <CountUp end={data?.tasks_completed || 0} duration={2} />
          </motion.div>
          <div style={{ fontSize: '11px', color: theme.textSecondary }}>
            任务完成
          </div>
        </div>

        <Divider style={{ margin: '12px 0' }} />

        <div style={{ fontSize: '12px' }}>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            marginBottom: '6px'
          }}>
            <span style={{ color: theme.textSecondary }}>数据处理</span>
            <span style={{ color: theme.textPrimary, fontWeight: '500' }}>
              {data?.data_processed || '0 MB'}
            </span>
          </div>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            marginBottom: '6px'
          }}>
            <span style={{ color: theme.textSecondary }}>API调用</span>
            <span style={{ color: theme.textPrimary, fontWeight: '500' }}>
              {data?.api_calls?.toLocaleString() || 0}
            </span>
          </div>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between'
          }}>
            <span style={{ color: theme.textSecondary }}>成功率</span>
            <Badge
              status={data?.success_rate > 95 ? "success" : data?.success_rate > 80 ? "warning" : "error"}
              text={
                <span style={{ fontWeight: '500' }}>
                  {data?.success_rate || 0}%
                </span>
              }
            />
          </div>
        </div>
      </CustomCard>
    </motion.div>
  );

  // 定义图表数据接口
  interface ChartDataPoint {
    x: string;
    y: number;
  }

  interface PieChartData {
    type: string;
    value: number;
    color?: string;
  }

  interface ColumnChartData {
    category: string;
    value: number;
    color?: string;
  }

  // 图表数据状态
  const [lineData, setLineData] = useState<ChartDataPoint[]>([]);
  const [pieData, setPieData] = useState<PieChartData[]>([]);
  const [columnData, setColumnData] = useState<ColumnChartData[]>([]);

  // 获取图表数据
  const fetchChartData = useCallback(async () => {
    try {
      // 模拟折线图数据 - 用户活跃度趋势
      const lineDataSample = [
        { x: '00:00', y: 10 },
        { x: '04:00', y: 25 },
        { x: '08:00', y: 40 },
        { x: '12:00', y: 30 },
        { x: '16:00', y: 50 },
        { x: '20:00', y: 35 },
        { x: '24:00', y: 45 },
      ];
      
      // 模拟饼图数据 - 用户设备分布
      const pieDataSample = [
        { type: '移动端', value: 45, color: '#1890ff' },
        { type: '桌面端', value: 30, color: '#52c41a' },
        { type: '平板端', value: 15, color: '#722ed1' },
        { type: '其他', value: 10, color: '#faad14' },
      ];
      
      // 模拟柱状图数据 - 每日访问量
      const columnDataSample = [
        { category: '周一', value: 120, color: '#1890ff' },
        { category: '周二', value: 132, color: '#52c41a' },
        { category: '周三', value: 101, color: '#722ed1' },
        { category: '周四', value: 134, color: '#faad14' },
        { category: '周五', value: 90, color: '#f5222d' },
        { category: '周六', value: 230, color: '#13c2c2' },
        { category: '周日', value: 210, color: '#eb2f96' },
      ];
      
      setLineData(lineDataSample);
      setPieData(pieDataSample);
      setColumnData(columnDataSample);
    } catch (error) {
      console.error('获取图表数据失败:', error);
    }
  }, []);

  // 初始化数据
  useEffect(() => {
    fetchDashboardStats();
    fetchSystemStats();
    fetchActivities();
    fetchQuickStats();
    fetchChartData(); // 添加图表数据获取
  }, [fetchDashboardStats, fetchSystemStats, fetchActivities, fetchQuickStats, fetchChartData]);

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.5 }}
      style={{
        padding: '24px',
        background: theme.contentBackground,
        minHeight: '100vh',
        boxShadow: 'inset 0 2px 4px rgba(0, 0, 0, 0.02)', // 添加内阴影增强层次感
      }}
    >
      {/* 页面标题和刷新按钮 */}
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: '32px',
        position: 'relative'
      }}>
        <motion.div
          initial={{ x: -50 }}
          animate={{ x: 0 }}
          transition={{ type: "spring", stiffness: 100 }}
        >
          <h1 style={{
            margin: 0,
            fontSize: '32px',
            fontWeight: 'bold',
            backgroundImage: `linear-gradient(135deg, ${theme.glowColor} 0%, ${theme.glowColor}aa 100%)`,
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text',
            display: 'flex',
            alignItems: 'center',
            gap: '12px'
          }}>
            <motion.div
              animate={{ rotate: 360 }}
              transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
              style={{
                width: '40px',
                height: '40px',
                borderRadius: '12px',
                background: `linear-gradient(135deg, ${theme.glowColor}20 0%, ${theme.glowColor}10 100%)`,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: '24px',
              }}
            >
              <DashboardOutlined style={{ color: theme.glowColor }} />
            </motion.div>
            系统控制台
          </h1>
          <div style={{
            fontSize: '14px',
            color: theme.textSecondary,
            marginTop: '8px',
            marginLeft: '52px'
          }}>
            实时监控系统运行状态和业务指标
          </div>
        </motion.div>

        <motion.div
          initial={{ x: 50 }}
          animate={{ x: 0 }}
          transition={{ type: "spring", stiffness: 100 }}
        >
          <Tooltip title="刷新所有数据">
            <Button
              type="primary"
              icon={
                <motion.div
                  animate={isRefreshing ? { rotate: 360 } : {}}
                  transition={{ duration: 1, repeat: isRefreshing ? Infinity : 0, ease: "linear" }}
                >
                  <ReloadOutlined />
                </motion.div>
              }
              onClick={refreshAllData}
              loading={isRefreshing}
              style={{
                borderRadius: '8px',
                background: `linear-gradient(135deg, ${theme.glowColor} 0%, ${theme.glowColor}dd 100%)`,
                border: 'none',
                boxShadow: `0 4px 16px ${theme.glowColor}40`,
              }}
              size="large"
            >
              刷新数据
            </Button>
          </Tooltip>
        </motion.div>
      </div>



      {/* 系统状态和快速统计 */}
      <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
        {/* 系统状态 */}
        <Col xs={24} lg={12}>
          <motion.div
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ delay: 0.5 }}
          >
            <CustomCard
              theme={theme}
              mode={mode}
              style={{
                height: '100%',
                overflow: 'hidden',
                position: 'relative',
              }}
            >
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '8px',
                marginBottom: '16px'
              }}>
                <FireOutlined style={{ color: theme.glowColor }} />
                <span style={{ 
                  fontSize: '16px', 
                  fontWeight: '500', 
                  color: theme.textPrimary 
                }}>
                  系统监控
                </span>
                <Badge status="processing" text="实时" style={{ marginLeft: 'auto' }} />
              </div>
              {loading.system ? (
                <Skeleton active paragraph={{ rows: 4 }} />
              ) : systemStats && (
                <div>
                  <SystemMonitorItem
                    label="CPU 使用率"
                    value={systemStats.cpu_usage}
                    icon={<DatabaseOutlined />}
                    color="#1890ff"
                  />

                  <SystemMonitorItem
                    label="内存使用"
                    value={systemStats.memory_used}
                    total={systemStats.memory_total}
                    icon={<CloudUploadOutlined />}
                    color="#52c41a"
                  />

                  <SystemMonitorItem
                    label="磁盘使用"
                    value={systemStats.disk_used}
                    total={systemStats.disk_total}
                    icon={<DatabaseOutlined />}
                    color="#722ed1"
                  />

                  <div style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(2, 1fr)',
                    gap: '12px',
                    marginTop: '16px',
                    padding: '16px',
                    background: `${theme.glowColor}05`,
                    borderRadius: '12px',
                    border: `1px solid ${theme.glowColor}20`,
                  }}>
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: '12px', color: theme.textSecondary, marginBottom: '4px' }}>
                        网络上传
                      </div>
                      <div style={{ fontSize: '16px', fontWeight: 'bold', color: theme.glowColor }}>
                        {systemStats.network_sent} MB
                      </div>
                    </div>
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: '12px', color: theme.textSecondary, marginBottom: '4px' }}>
                        网络下载
                      </div>
                      <div style={{ fontSize: '16px', fontWeight: 'bold', color: theme.glowColor }}>
                        {systemStats.network_recv} MB
                      </div>
                    </div>
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: '12px', color: theme.textSecondary, marginBottom: '4px' }}>
                        进程数
                      </div>
                      <div style={{ fontSize: '16px', fontWeight: 'bold', color: theme.glowColor }}>
                        {systemStats.processes}
                      </div>
                    </div>
                    <div style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: '12px', color: theme.textSecondary, marginBottom: '4px' }}>
                        运行时间
                      </div>
                      <div style={{ fontSize: '16px', fontWeight: 'bold', color: theme.glowColor }}>
                        {systemStats.uptime_days}天
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </CustomCard>
          </motion.div>
        </Col>

        {/* 快速统计 */}
        <Col xs={24} lg={12}>
          <motion.div
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ delay: 0.6 }}
          >
            <CustomCard
              theme={theme}
              mode={mode}
              style={{
                height: '100%',
                position: 'relative',
                overflow: 'hidden',
              }}
            >
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '8px',
                marginBottom: '16px'
              }}>
                <RocketOutlined style={{ color: theme.glowColor }} />
                <span style={{ 
                  fontSize: '16px', 
                  fontWeight: '500', 
                  color: theme.textPrimary 
                }}>
                  快速统计
                </span>
                <Tag color="blue" style={{ marginLeft: 'auto', borderRadius: '12px' }}>
                  实时更新
                </Tag>
              </div>
              {loading.quick ? (
                <Skeleton active paragraph={{ rows: 3 }} />
              ) : quickStats && (
                <Row gutter={[16, 16]}>
                  <Col span={12}>
                    <QuickStatCard
                      title="今日统计"
                      data={quickStats.today}
                      icon={<ClockCircleOutlined />}
                      color="#1890ff"
                    />
                  </Col>
                  <Col span={12}>
                    <QuickStatCard
                      title="昨日统计"
                      data={quickStats.yesterday}
                      icon={<SyncOutlined />}
                      color="#52c41a"
                    />
                  </Col>
                  <Col span={12}>
                    <QuickStatCard
                      title="本周统计"
                      data={quickStats.this_week}
                      icon={<BarChartOutlined />}
                      color="#722ed1"
                    />
                  </Col>
                  <Col span={12}>
                    <QuickStatCard
                      title="本月统计"
                      data={quickStats.this_month}
                      icon={<FundOutlined />}
                      color="#faad14"
                    />
                  </Col>
                </Row>
              )}
            </CustomCard>
          </motion.div>
        </Col>
      </Row>

      {/* 活动记录 */}
      <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
        <Col span={24}>
          <motion.div
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ delay: 0.7 }}
          >
            <CustomCard
              theme={theme}
              mode={mode}
              style={{
                height: '100%',
                overflow: 'hidden',
                position: 'relative',
              }}
              bodyStyle={{ padding: '0' }}
            >
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '8px',
                padding: '20px',
                paddingBottom: '0'
              }}>
                <ClockCircleOutlined style={{ color: theme.glowColor }} />
                <span style={{ 
                  fontSize: '16px', 
                  fontWeight: '500', 
                  color: theme.textPrimary 
                }}>
                  最近活动
                </span>
                <Badge status="processing" text="实时" style={{ marginLeft: 'auto' }} />
              </div>
              {loading.activities ? (
                <Skeleton active paragraph={{ rows: 4 }} style={{ padding: '20px' }} />
              ) : (
                <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
                  <Timeline
                    style={{ padding: '20px' }}
                    items={activities.map((activity, index) => ({
                      dot: (
                        <div style={{
                          width: '32px',
                          height: '32px',
                          borderRadius: '50%',
                          background: `linear-gradient(135deg, ${theme.glowColor}20 0%, ${theme.glowColor}10 100%)`,
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          fontSize: '16px',
                          color: theme.glowColor,
                        }}>
                          {getActivityIcon(activity.type, activity.status, iconColors)}
                        </div>
                      ),
                      children: (
                        <motion.div
                          initial={{ opacity: 0, x: -20 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: index * 0.1 }}
                        >
                          <div style={{
                            padding: '16px',
                            borderRadius: '12px',
                            background: `linear-gradient(135deg, ${theme.cardBackground} 0%, ${theme.cardBackground}ee 100%)`,
                            border: `1px solid ${theme.cardBorder}`,
                            marginBottom: '12px',
                            position: 'relative',
                            overflow: 'hidden',
                          }}>
                            <div style={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'flex-start',
                              marginBottom: '12px'
                            }}>
                              <div>
                                <div style={{
                                  fontSize: '16px',
                                  fontWeight: '500',
                                  color: theme.textPrimary,
                                  marginBottom: '4px'
                                }}>
                                  {activity.title}
                                </div>
                                <div style={{
                                  fontSize: '14px',
                                  color: theme.textSecondary
                                }}>
                                  {activity.description}
                                </div>
                              </div>
                              <div style={{ display: 'flex', gap: '8px' }}>
                                {getActivityTag(activity.status)}
                                <Tag color="default" style={{ borderRadius: '12px' }}>
                                  {formatTime(activity.timestamp)}
                                </Tag>
                              </div>
                            </div>
                            <div style={{
                              display: 'flex',
                              alignItems: 'center',
                              gap: '8px',
                              fontSize: '12px',
                              color: theme.textTertiary
                            }}>
                              <Avatar size="small" icon={<UserOutlined />} />
                              <span>用户ID: {activity.user_id}</span>
                            </div>
                          </div>
                        </motion.div>
                      )
                    }))}
                  />
                </div>
              )}
            </CustomCard>
          </motion.div>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[24, 24]}>
        <Col span={24}>
          <motion.div
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ delay: 0.8 }}
          >
            <CustomCard
              theme={theme}
              mode={mode}
              style={{
                height: '100%',
                overflow: 'hidden',
                position: 'relative',
              }}
            >
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '8px',
                marginBottom: '16px'
              }}>
                <BarChartOutlined style={{ color: theme.glowColor }} />
                <span style={{ 
                  fontSize: '16px', 
                  fontWeight: '500', 
                  color: theme.textPrimary 
                }}>
                  数据可视化
                </span>
                <Tag color="blue" style={{ marginLeft: 'auto', borderRadius: '12px' }}>
                  实时数据
                </Tag>
              </div>
              
              <Row gutter={[16, 16]}>
                <Col xs={24} lg={8}>
                  <CustomLineChart 
                    data={lineData} 
                    title="用户活跃度趋势" 
                    height={300}
                    color="#1890ff"
                  />
                </Col>
                <Col xs={24} lg={8}>
                  <CustomPieChart 
                    data={pieData} 
                    title="用户设备分布" 
                    height={300}
                  />
                </Col>
                <Col xs={24} lg={8}>
                  <CustomColumnChart 
                    data={columnData} 
                    title="每日访问量" 
                    height={300}
                  />
                </Col>
              </Row>
            </CustomCard>
          </motion.div>
        </Col>
      </Row>
    </motion.div>
  );
};

export default EnhancedDashboard;